package com.esp.studentManagementSystem.controller;

import com.esp.studentManagementSystem.exception.ForbiddenException;
import com.esp.studentManagementSystem.exception.UnauthorizedException;
import com.esp.studentManagementSystem.pojo.vo.ApiResponseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class MyErrorController {
    private static final Logger log = LoggerFactory.getLogger(MyErrorController.class);

    @ExceptionHandler(UnauthorizedException.class)
    public ResponseEntity<ApiResponseVO> handleUnauthorizedException(UnauthorizedException e) {
        log.error("401：{}", e.getMessage());
        ApiResponseVO apiResponse = new ApiResponseVO();
        apiResponse.setSuccess(false);
        apiResponse.setMessage(e.getMessage());
        return new ResponseEntity<>(apiResponse, HttpStatus.UNAUTHORIZED);
    }

    @ExceptionHandler(ForbiddenException.class)
    public ResponseEntity<ApiResponseVO> handleRuntimeException(ForbiddenException e) {
        log.error("403：{}", e.getMessage());
        ApiResponseVO apiResponse = new ApiResponseVO();
        apiResponse.setSuccess(false);
        apiResponse.setMessage(e.getMessage());
        return new ResponseEntity<>(apiResponse, HttpStatus.FORBIDDEN);
    }

//    @ExceptionHandler(Exception.class)
//    @ResponseBody
//    public ResponseEntity<String> handleException(Exception e) {
//        String errorMessage = "发生错误，请联系管理员或稍后重试。";
//        log.error("发生异常：{}", e.getMessage());
//        return ResponseEntity.status(HttpStatus.NOT_FOUND)
//                .contentType(MediaType.APPLICATION_JSON)
//                .body(errorMessage);
//    }
}
